import React, {FC, useContext, useEffect, useState} from 'react';
import "./index.less";
import {Button, Divider, Form, Space, Tag} from "antd";
import {correspVal} from "@/utils/biz";
import * as API from "@/services";
import * as numeral from "numeral";
import {CheckCard} from "@ant-design/pro-components";
import HxIcon from "@/components/HxIcon";
import {KfModal, useBackendEnum} from "kf-web-library";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import MallOrderPendingPayinfo from "@/pages/MallPage/MallOrder/MallOrderPendingPayinfo";
import {useRequest} from "ahooks";
import {MallJournalPeriodPickerValueType} from "@/components/HxMallJournalPeriodPicker";
import {FormattedMessage} from "@@/exports";


export type OrderConfirmInfo = {
  displayType: string;
  timeType: string;
  journal: API.FrontJournal;
  plan?: API.FrontJournalSubscribePlan;
  periods: MallJournalPeriodPickerValueType[];
}

interface MallOrderConfirmInfoProps {
  orderConfirmInfo: OrderConfirmInfo;
  onCancel?: () => void;
}

const MallOrderConfirmInfo: FC<MallOrderConfirmInfoProps> = (props) => {
  const {orderConfirmInfo, onCancel} = props;
  const {isZhCN} = useContext(HxConfigContext)
  const {enumDict, enumTypeDict, getBackendEnum} = useBackendEnum();
  const [pendingPayInfo, setPendingPayInfo] = useState<API.JournalSubscribe_Response | undefined>(undefined);

  const paywayTypes = [
    {
      name:  <FormattedMessage id="text.alipay"/>,
      value: "2",
      label: <FormattedMessage id="text.alipay-pay"/>,
      icon: <HxIcon type={"hxicon-zhifubaozhifu"} style={{fontSize: 32}}/>,
      iconUrl: "/payment/alipay.png",
    },
    {
      name:  <FormattedMessage id="text.wechat"/>,
      value: "3",
      label: <FormattedMessage id="text.wechat-pay"/>,
      icon: <HxIcon type={"hxicon-weixinzhifu"} style={{fontSize: 32}}/>,
      iconUrl: "/payment/wechat.png",
    },
  ]

  const subscribeJournalReq = useRequest((p) => API.subscribeJournal(p), {
    manual: true,
  })

  useEffect(() => {
    return () => {
      setPendingPayInfo(undefined);
    }
  }, []);

  return (
    <div className={"order-confirm-info-container"}>
      <Form
        initialValues={{
          payway: "2",
        }}
        onFinish={(values) => {
          const paywayType = paywayTypes.find(p => p.value === values.payway)
          /*setPendingPayInfo({
            expirationSecond: 200,
            isSuccess: true,
            netAmount: "",
            qrCode: "12121212",
            orderNo: "111212",
            subject: "111212",
            payway: values.payway,
            qrCodeImageUrl: "tttttt",
            totalAmount: "111",

            paywayStr: paywayType?.name,
            qrCodeIcon: paywayType?.iconUrl
          })*/

          subscribeJournalReq.runAsync({
            displayType: orderConfirmInfo.displayType, //订阅呈现类型 SubscribeDisplayType
            timeType: orderConfirmInfo.timeType, //订阅时间类型 SubscribeTimeType
            journalId: orderConfirmInfo?.journal.id, //期刊ID
            planId: orderConfirmInfo.timeType === "FUTURE" ? orderConfirmInfo.plan?.id : undefined, //订阅套餐ID
            periodIds: orderConfirmInfo.timeType === "HISTORICAL" ? orderConfirmInfo.periods?.map((period) => period.value) : undefined, //刊期ID集合
            payway: values.payway, //支付方式 内容为数字的字符串 2:支付宝 3:微信
          }).then((resp) => {
            if (resp.flag) {
              setPendingPayInfo({
                ...resp.data,
                paywayStr: paywayType?.name,
                qrCodeIcon: paywayType?.iconUrl
              })
            }
          })
        }}
      >
        <div className={"oci-content"}>
          <div className={"oci-content-title"}><FormattedMessage id="mall.SubscriptionConfirmation"/></div>
          <Divider/>
          <div className={"oci-desc-title"}><FormattedMessage id="mall.SubscriptionItems"/></div>
          <div className={"oci-desc-items"}>
            <div className={"oci-desc-item"}>
              <span className={"oci-desc-item-label"}><FormattedMessage id="mall.SubscriptionJournalName"/>:</span>
              <span
                className={"oci-desc-item-content"}>{correspVal(isZhCN, orderConfirmInfo.journal?.journalNameCn, orderConfirmInfo.journal?.journalNameEn)}</span>
            </div>
            <div className={"oci-desc-item"}>
              <span className={"oci-desc-item-label"}><FormattedMessage id="mall.SubscriptionCarrier"/>:</span>
              <span className={"oci-desc-item-content"}>{getBackendEnum("SubscribeDisplayType", orderConfirmInfo.displayType)?.i18EnumDesc}</span>
            </div>
            <div className={"oci-desc-item"}>
              <span className={"oci-desc-item-label"}><FormattedMessage id="mall.SubscriptionPeriod"/>:</span>
              <span className={"oci-desc-item-content"}>{getBackendEnum("SubscribeTimeType", orderConfirmInfo.timeType)?.i18EnumDesc}</span>
            </div>
            <div className={"oci-desc-item"}>
              <span className={"oci-desc-item-label"}><FormattedMessage id="mall.SubscriptionSelect"/>:</span>
              <span className={"oci-desc-item-content"}>
                {orderConfirmInfo.timeType === "FUTURE"  && orderConfirmInfo.plan?.planName}
                {orderConfirmInfo.timeType === "HISTORICAL"  && (
                  <div className={"oci-historical-period-dp"}>
                    <div className={"oci-historical-period-dp-title"}>
                      <FormattedMessage id="journal.period-info.aggregate-by-issue-desc" values={{total: orderConfirmInfo.periods?.length}}/>
                    </div>
                    <div className={"oci-historical-period-dp-content"}>
                      {orderConfirmInfo.periods?.map((period) => (
                        <Tag key={period.value}>{period.label}</Tag>
                      ))}
                    </div>
                  </div>
                )}
              </span>
            </div>
          </div>
          <Divider/>
          <div className={"oci-desc-title"}> <FormattedMessage id="mall.SubscriptionOrderSummary"/></div>
          <div className={"oci-desc-items"}>
            <div className={"oci-desc-item"}>
              <span className={"oci-desc-item-label"}><FormattedMessage id="mall.SubscriptionTotalOrderAmount"/>:</span>
              <span className={"oci-desc-item-content"}>
                {(orderConfirmInfo.timeType === "FUTURE" && orderConfirmInfo.plan) && (
                  <>
                    ￥{numeral(orderConfirmInfo.plan?.totalPrice / 100).format('0.00')}
                  </>
                )}
                {(orderConfirmInfo.timeType === "HISTORICAL" && orderConfirmInfo.periods?.length > 0) && (
                  <>
                    ￥{numeral(((orderConfirmInfo.journal.regularPrice || 0) * orderConfirmInfo.periods?.length) / 100).format('0.00')}
                  </>
                )}
              </span>
            </div>
            {/*<div className={"oci-desc-item"}>
                    <span className={"oci-desc-item-label"}>折扣金额:</span>
                    <span className={"oci-desc-item-content"}>
                      -￥{numeral(orderConfirmInfo.plan?.totalPrice / 100).format('0.00')}
                    </span>
                  </div>*/}
            {/*<div className={"oci-desc-item"}>
                    <span className={"oci-desc-item-label"}>支付合计:</span>
                    <span className={"oci-desc-item-content"}>
                      ￥{numeral(orderConfirmInfo.plan?.totalPrice / 100).format('0.00')}
                    </span>
                  </div>*/}
          </div>
          <Divider/>
          <div className={"oci-desc-title"}><FormattedMessage id="mall.SubscriptionOrderPaymentMethod"/></div>
          <Form.Item shouldUpdate={true}>
            {({getFieldValue}) => {
              return (
                <Form.Item name={"payway"} getValueFromEvent={(v) => {
                  //阻止CheckCard反选, 确保payway肯定有值
                  return !v ? getFieldValue("payway") : v;
                }}>
                  <CheckCard.Group
                    size={"small"}
                  >
                    {
                      paywayTypes.map((payway) => {
                        return <CheckCard
                          key={payway.value}
                          title={<>
                            {payway.label}
                          </>}
                          avatar={payway.icon}
                          value={payway.value}
                        />
                      })
                    }
                  </CheckCard.Group>
                </Form.Item>
              )
            }}
          </Form.Item>
        </div>
        <div className={"oci-footer"}>
          <Space>
            <Button
              loading={subscribeJournalReq.loading}
              className={"oci-confirm-btn"}
              type={"primary"}
              htmlType={"submit"}
            >
              <FormattedMessage id="text.online-pay"/>
            </Button>
            <Button className={"oci-cancel-btn"} onClick={() => {
              setPendingPayInfo(undefined);
              onCancel?.();
            }}>
              <FormattedMessage id="text.cancel"/>
            </Button>
          </Space>

        </div>
      </Form>

      {
        !!pendingPayInfo && (
          <KfModal
            title={null}
            open={true}
            destroyOnClose={true}
            onCancel={() => setPendingPayInfo(undefined)}
            width={400}
          >
            <MallOrderPendingPayinfo pendingPayInfo={pendingPayInfo}/>
          </KfModal>
        )
      }
    </div>
  );
};

export default MallOrderConfirmInfo;
